﻿App.User = function() {
    return {

        currentFormValues: {},

        getStore: function() {
            var store = new Ext.data.Store({
            	autoLoad:true,
				baseParams:{start:0, limit:20},
				proxy: new Ext.data.HttpProxy({
					url : 'user/users'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'staff_id',
					fields: [{
						name: 'staff_id',
						type: 'string'
					},
					{
						name: 'staff_code',
						xtype : 'numberfield',
						allowBlank: false
					},
					{
						name: 'tell_nbr',
						xtype : 'numberfield',
						allowBlank: false
					},
					{
						name: 'name',
						allowBlank: false
					},
					{
						name: 'emp_date',
						type: 'date',
						dateFormat: 'time'
					},
					{
						name: 'roles'
					},
					{
						name: "roleList",
						convert: this.roleList
					}]
				})
            });
            return store;
        },

        roleList: function(value, rec) {
            var list = "";
            for (var i = 0; i < rec.roles.length; i++) {
                list += rec.roles[i].name + ",";
            }
            return list.substr(0, list.length - 1);
        },
        
        getForm: function() {
            var form = new Ext.form.FormPanel({
			url:'user/save',
			labelAlign: 'right',
			buttonAlign:'center',
			frame: true,
//			layout:'fit',
			waitMsgTarget:true,
			items: [
			{
				layout:'column',
				//  defaults:{allowBlank :false},
				items:[
				{
					columnWidth:.5,
					layout: 'form',
					defaultType : 'textfield',
					items : [
					{
						xtype: 'hidden',
						name: 'staff_id',
						value: ''
					}, 
					{
						name: 'name',
						fieldLabel: '员户名称',
						allowBlank:false,
						width:250,
						listeners: 
						{
						    scope: this,
						    keypress: function(field, e) 
						    {
						        if (e.getKey() == 13) 
						        {
						        	var obj = this.form.getForm.findField("password");
						        	if (obj) obj.focus();
						        }
						    }
						}
					}, 
					{    
						inputType: 'password',
						name: 'password',
						fieldLabel: '密码',
						id: 'password',
						width:250,
						allowBlank: true,
						listeners: 
						{
						    scope: this,
						    keypress: function(field, e) 
						    {
						    	if (e.getKey() == 13) 
						    	{
						    		var obj = this.form.getForm().findField("confirmPassword");
				                        if (obj) obj.focus();
						    	}
						    }
						}
					}, 
					{
						name: 'identid',
						width:250,
						fieldLabel: '身份证',
						value:'0'
					}, 
					{
						xtype:'datefield',
						format:"Y-m-d",
						name: 'born',
						width:250,
						fieldLabel: '出生年月日'
					},
					{
					     name: 'tell_nbr',
					     width:250,
						xtype : 'numberfield',
						fieldLabel: '电话号',
						value:'0'
					}, 
					{
						name: 'emerg',
						width:250,
						fieldLabel: '紧急联系人',
						value:'0'
					}, 
					{
						name: 'hight',
						width:250,
						xtype : 'numberfield',
						fieldLabel: '身高',
						value:'0'
					}]
				  },
				  {
					  columnWidth:.5,
					  layout: 'form',
					  width:250,
					  defaultType : 'textfield',
					  items : [ 
					  {  
						name: 'staff_code',
						width:250,
						xtype : 'numberfield',
						fieldLabel: '员工编码'
					  }, 
					  {
						inputType: 'password',
						width:250,
						name: 'confirmPassword',
						fieldLabel: '确认密码',
						vtype: 'password',
						allowBlank: true,
						initialPassField: 'password',
						listeners: 
						{
						    scope: this,
						    keypress: function(field, e) 
						    {
						        if (e.getKey() == 13) 
						        {
						            var obj = this.form.getForm().findField("roleList");
			                        if (obj) obj.focus();
			                     }
						    }
						}
					  }, 
					  {
						  name: 'addr',
						  width:250,
						  fieldLabel: '住址'
					  }, 
					  {
						xtype:'datefield',
						format:"Y-m-d",
						width:250,
						name: 'emp_date',
						fieldLabel: '入职时间',
						value:'0'
					  },  
					  {
						  name: 'area',
						  width:250,
						  fieldLabel: '归属'
					  }, 
					  {
						  name: 'home_nbr',
						  width:250,
						  xtype : 'numberfield',
						  fieldLabel: '紧急联系电话',
							value:'0',
						  listeners: 
						  {
						  	scope: this,
						    keypress: function(field, e) 
						    {
						        if (e.getKey() == 13) 
						        {
						            var obj = this.form.getForm.findField("password");
						            if (obj) obj.focus();
						        }
						    }
						}
					  }, 
					  {
						  name: 'weight',
						  width:250,
						  xtype : 'numberfield',
						  fieldLabel: '体重',
						  value:'0'
					  }]
				  }]
			},
			{
				xtype: 'panel',
//				width: 900,
				 height:300,
				layout: 'fit',
				 bodyStyle : 'width:100%', 
				layout: {
                    type:'vbox',
                    padding:'5',
                    pack:'end',
                    align:'center'
                },
				items: [
				{
					xtype: 'multiselect',
					name: 'roleList',
					align:'center',
					allowBlank: true,
					width: 500,
					 height:250,
					enableKeyEvents: true,
					valueField: "post_id",
					displayField: "name",
					tbar: ["选择角色"],
					store: new Ext.data.Store(
					{
						autoLoad: false,
					    remoteSort: false,
						proxy: new Ext.data.HttpProxy(
						{
							url : 'role/roleList'
						}),
						reader: new Ext.data.JsonReader(
						{
							totalProperty : 'totalCount',
							root : 'rows',
							idProperty : 'post_id',
							fields: [
							{
								name: 'post_id'
							},
							{
								name: 'name'
							}]
						})
					}),
					listeners: 
					{
			            scope: this,
			            keypress: function(field, e) 
			            {
			                if (e.getKey() == 13) 
			                {
			                    this.submit();
			                }
			            }
					}
				}]
			} ],
            buttons: [{
                text: '确定',
                scope: this,
                handler: function() {
                    this.submit();
                }
            },
            {
                text: '重置',
                scope: this,
                handler: function() {
                    var f = this.form.getForm();
                    f.reset();
                    f.setValues(this.currentFormValues);
                    f.clearInvalid();
                }
            }]
        });
        	return form;
        },

        submit: function() {
            if (this.form.getForm().isValid()) {
            	if(this.form.getForm().findField("roleList").getValue().split(",").length!=1){
            		Ext.Msg.alert('提示', "请选择一个角色");
            		return;
            	}
                this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                        var info = action.result.info;
                        if (action.result.success) {
                            this.store.reload();
                            if (action.result.method == "Create") {
                                this.form.getForm().reset();
                            } else {
                                this.dlg.hide();
                            }
                        }
                        Ext.Msg.alert('信息', info);
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });
            }
        },

        getDialog: function() {
            var dlg = new Ext.Window({
                width: 700,
                height: 560,
                maximized:true,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.form],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.form.getForm().waitMsgTarget = fp.getEl();
                    },
                    show: function() {
                        var f = this.form.getForm();
                        f.findField("roleList").store.reload();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
//                        if (this.currentFormValues.id) {
//                            Ext.get("pwdMsg").dom.innerHTML = "<span style='color:red;line-height:30px;'>*如果不修改密码请不要输入密码和确认密码</span>";
//                            f.findField("password").allowBlank = true;
//                            f.findField("confirmPassword").allowBlank = true;
//                        } else {
//                            f.findField("password").allowBlank = false;
//                            f.findField("confirmPassword").allowBlank = false;
//                            Ext.get("pwdMsg").dom.innerHTML = "<span style='color:red;'></span>";
//                        }
                    }
                }
            });
            return dlg;
        },
        highLight: function(value) {
            var key = App.User.grid.store.baseParams.query;
            var v = value ? value.toString() : '';
            if (Ext.isString(v) & Ext.isString(key)) {
                if (key.length > 0) {
                    var re = new RegExp(key, "g");
                    return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
                } else {
                    return v;
                }
            } else {
                return v;
            }
        },
        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.CheckboxSelectionModel();

            this.grid = new Ext.grid.GridPanel({
            	tbar: new Ext.PagingToolbar({
            		pageSize: 20 ,//分页必须加的参数.最好和store里面的limit保持一致
                    displayInfo: true,
                    store: this.store,
                    items: ['-', 
                          {
                        text: '增加',
                        scope: this,
                        handler: this.add
                    },
//                    {
//                        text: '编辑',
//                        scope: this,
//                        handler: this.edit
//                    },
                    {
                        text: '删除',
                        scope: this,
                        handler: this.del
                    },
                    '-', new Ext.ux.form.SearchField({
                        store: this.store,
                        width: 110
                    })]
                }),
                title:"用户管理",//打印必须设置tile
                plugins: [Ext.ux.plugins.Print],//打印按钮
                loadMask: true,
                viewConfig : {autoFill:false,forceFit:true},
                autoHeight:true,
                store: this.store,
                sm: sm,
                columns: [sm, new Ext.grid.RowNumberer(),{
                    header: "员工编码",
//                    width: 80,
                    sortable: true,
                    dataIndex: 'staff_code',
                    renderer:this.highLight
                },
                {
                    header: "用户名称",
//                    width: 100,
                    sortable: true,
                    dataIndex: 'name',
                    renderer:this.highLight
                },
                {
                    header: "联系电话",
//                    width: 100,
                    sortable: true,
                    dataIndex: 'tell_nbr',
                    renderer:this.highLight
                },
                {
                    header: "入职日期",
//                    width: 100,
                    sortable: true,
                    dataIndex: 'emp_date',
                    renderer: Ext.util.Format.dateRenderer('Y-m-d')
                },
                {
                    header: "职位",
//                    width: 100,
                    sortable: true,
                    dataIndex: 'roleList',
                    renderer:this.highLight
                }]
            });
            panel.add(this.grid);

        },
        
        add: function() {
            Ext.apply(this.currentFormValues, {
                id: '',
                name: "",
                password: "",
                confirmPassword: "",
                roleList: ""
            });
            this.dlg.setTitle("增加员工");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑用户");
                var rec = this.grid.getSelectionModel().getSelected();
                var ml = [];
                for (var i = 0; i < rec.data.roles.length; i++) {
                    ml.push(rec.data.roles[i].staff_id);
                }
                Ext.apply(this.currentFormValues, {
                	staff_id: rec.data.id,
                    name: rec.data.name,
                    password: "",
                    confirmPassword: "",
                    roleList: ml.toString()
                });
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的用户。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelections();
                var ids = [];
                var titles = '';
                for (var i = 0; i < recs.length; i++) {
                    var data = recs[i].data;
                    ids.push(data.staff_id);
                    titles += data.name + '<br>';
                }
                Ext.Msg.confirm('删除用户', '确定删除以下用户？<br><font color="red">' + titles + '</font>',
                function(btn) {
                    if (btn == 'yes') {
						Ext.Ajax.request({
							method:'post',
							url:'user/remove',
							params:{
								ids:ids.toString()
							},
							success: function(resp, opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								if(result.success=='true') {
									Ext.Msg.alert('信息', info);
                                    App.User.store.reload();
								}else {
                                    Ext.Msg.alert('信息', info);
                                }
							},
							failure: function(resp,opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								Ext.Msg.alert('提示', info); 
							}
						});
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的用户！');
            }
        },

        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            };
            if (!this.form) {
                this.form = this.getForm();
            };
            if (!this.dlg) {
                this.dlg = this.getDialog();
            };
            this.createGrid(id);

        }
    };
} ();
